<?php

namespace App\Repositories\Manage;

use App\Models\Spec;
use App\Models\SpecItem;

class SpecRepository
{

    /**
     * 增加规格
     * @param int $product_i
     * @param $skus
     */
    public function updateMappings(int $product_id, $skus)
    {
        if (!$product_id) return retFail("参数错误");
        $specIds = Spec::query()->where("product_id", $product_id)->pluck("id")->toArray();
        if (isset($specIds)) {
            $specIds_1 = get_column($skus, "id");
            settype($specIds, "array");
            settype($specIds_1, "array");
            $spec_ids = array_diff($specIds, $specIds_1 ?? []);

            if ($spec_ids) {
                SpecItem::query()->whereIn("spec_id", $specIds)->update(['is_delete' => 1]);
                Spec::query()->whereIn("id", $spec_ids)->delete();
            }
        }

        $mappings = [];
        foreach ($skus as $k => $v) {
            if ($v['id']) {
                SpecItem::where(['spec_id' => $v['id']])->update(['is_delete' => 1]);
                $spec_id = intval($v['id']);

                Spec::query()->where(['id' => $spec_id])->update([
                    'title' => $v['title'],
                    'deleted_at' => NULL,
                ]);
            } else {
                $spec_id = Spec::create(['title' => $v['title'], 'product_id' => $product_id])->id;
            }
            if (!$spec_id) continue;

            foreach ($v['spec_items'] as $sv) {

                if ($sv['id']) {
                    SpecItem::where(['id' => $sv['id']])->update([
                        'title' => $sv['title'],
                        'price' => $sv['price'] ?? 0,
                        'spec_id' => $spec_id,
                        'is_delete' => 2,
                    ]);
                    continue;
                }

                SpecItem::create([
                    'title' => $sv['title'],
                    'price' => $sv['price'] ?? 0,
                    'spec_id' => $spec_id
                ]);
            }

        }

        return retSuc($mappings);

    }

    /**
     * 产品对应规格
     * @param int $product_id
     */
    public function getSpecs(int $product_id = 0)
    {
        if (!$product_id)
            return null;

        $specs = Spec::query()->where(['product_id' => $product_id])->get(['id', 'title']);
        if (!isset($specs))
            return null;

        foreach ($specs as $k => &$v) {
            $v['spec_items'] = SpecItem::query()->where(['spec_id' => $v['id'], 'is_delete' => 2])->get(['id', 'title', 'price']);

            foreach ($v['spec_items'] as $sk => &$sv) {
                $sv['price'] = formatNum($sv['price']);
            }
        }

        return $specs;
    }

}
